I am trying to add a div inside the main div on page loading, it works when i write the code like this:
function DivAdder() {
$('#mainDiv').append('<div class="newspaper-wrapper"></div>');
}
DivAdder();
window.onload = DivAdder;
But i want to make this function have a parameter so i can just pass its name instead of writing the whole string in .append function. I wrote something like this but i am having the error from the title:
function DivAdder(variable) {
$('#mainDiv').append($(variable));
}
DivAdder('<div class="newspaper_wrapper"></div>');
window.onload = DivAdder;
And i tried this as well:
$('#mainDiv').append(variable);
But nothing happens. I read some documentation but was not successful. Appreciate the help <3 .
This is because window.onload passes an Event object as first argument. If you console.log(variable), it will tell you it's an Event.
You need to keep this first argument as an optional event, and pass your HTML as second argument :
function DivAdder($event, html) {
console.log("Event = ", $event)
console.log("Adding div : " , html)
$('#mainDiv').append(html);
}
DivAdder(null, '<div class="newspaper_wrapper">TEST</div>');
window.onload = DivAdder; // This will call DivAdder( LoadEvent )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mainDiv"></div>
I'm not sure why you're assigning window.onload = DivAdder in the first place, since this won't add any HTML and won't do anything at all. You can get rid of it completely, it's only causing trouble.
function DivAdder(html) {
console.log("Adding div : " , html)
$('#mainDiv').append(html);
}
DivAdder('<div class="newspaper_wrapper">TEST</div>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mainDiv"></div>